package com.smarth.zhizulian.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

import com.smarth.zhizulian.R;

/**
 * Created by 18865 on 2017/12/21.
 */

public class ScaleImageView extends android.support.v7.widget.AppCompatImageView {
    private float mScaleWidth;
    private float mScaleHeight;

    public ScaleImageView(Context context) {
        this(context, null);
    }

    public ScaleImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScaleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ScaleImageView);
        mScaleWidth = a.getInt(R.styleable.ScaleImageView_scaleWidth, 1);
        mScaleHeight = a.getInt(R.styleable.ScaleImageView_scaleHeight, 1);
        a.recycle();

    }

    //传入参数widthMeasureSpec、heightMeasureSpec
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        float scale = mScaleHeight / mScaleWidth;
        int widthMeasure = MeasureSpec.getSize(widthMeasureSpec);
        int heightMeasure = (int) (widthMeasure * scale);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightMeasure, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
